import { useState, useEffect, useRef, useCallback } from 'react';

/**
 * 设备类型枚举
 */
const DEVICES = {
    MOBILE: 'mobile',
    TABLET: 'tablet',
    DESKTOP: 'desktop'
};

// 缓存用户代理检测结果，避免重复正则匹配
let cachedUserAgentInfo = null;
const getUserAgentInfo = () => {
    if (cachedUserAgentInfo === null) {
        const userAgent = navigator.userAgent.toLowerCase();
        cachedUserAgentInfo = {
            isTablet: /ipad|android.*tablet|kindle|silk|playbook/i.test(userAgent),
            isMobile: /mobile|android|iphone|ipod|blackberry|windows phone|opera mini|iemobile/i.test(userAgent)
        };
    }
    return cachedUserAgentInfo;
};

/**
 * 检测设备类型的核心函数
 */
const detectDeviceType = () => {
    const screenWidth = window.innerWidth;
    const { isTablet, isMobile } = getUserAgentInfo();

    // 平板设备检测
    if (isTablet && screenWidth >= 768) {
        return DEVICES.TABLET;
    }

    // 移动设备检测
    if (isMobile) {
        if (screenWidth < 768) {
            return DEVICES.MOBILE;
        }
        if (screenWidth < 1024) {
            return DEVICES.TABLET;
        }
    }

    // 基于屏幕尺寸的判断
    if (screenWidth < 768) {
        return DEVICES.MOBILE;
    } else if (screenWidth < 1024) {
        return DEVICES.TABLET;
    } else {
        return DEVICES.DESKTOP;
    }
}

/**
 * 简化版设备检测Hook - 只返回设备类型
 * @returns {string} 设备类型: 'mobile' | 'tablet' | 'desktop'
 */
export default () => {
    const [deviceType, setDeviceType] = useState(() => detectDeviceType());
    const timeoutRef = useRef(null);
    const lastWidthRef = useRef(window.innerWidth);

    const handleResize = useCallback(() => {
        const currentWidth = window.innerWidth;
        
        // 如果宽度变化不大，跳过检测（优化性能）
        if (Math.abs(currentWidth - lastWidthRef.current) < 10) {
            return;
        }
        
        lastWidthRef.current = currentWidth;
        
        if (timeoutRef.current) {
            clearTimeout(timeoutRef.current);
        }
        
        timeoutRef.current = setTimeout(() => {
            const newDeviceType = detectDeviceType();
            // 只有当设备类型真正改变时才更新状态
            setDeviceType(prevType => {
                return prevType !== newDeviceType ? newDeviceType : prevType;
            });
        }, 150); // 增加防抖延迟，减少频繁触发
    }, []);

    useEffect(() => {
        window.addEventListener('resize', handleResize, { passive: true });
        window.addEventListener('orientationchange', handleResize, { passive: true });

        return () => {
            window.removeEventListener('resize', handleResize);
            window.removeEventListener('orientationchange', handleResize);
            if (timeoutRef.current) {
                clearTimeout(timeoutRef.current);
            }
        };
    }, [handleResize]);

    return deviceType;
};

// 导出设备类型常量供外部使用
export { DEVICES };